package com.chcit.mobile.mvp.receive.model;

import android.app.Application;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.app.utils.FormatStringUtil;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.BaseResponse;
import com.chcit.mobile.mvp.entity.PageBean;
import com.chcit.mobile.mvp.entity.ReceiveBean;
import com.chcit.mobile.mvp.entity.ResponseBean;
import com.chcit.mobile.mvp.entity.ResultBean;
import com.chcit.mobile.mvp.receive.Entity.AsnResultBean;
import com.chcit.mobile.mvp.receive.Entity.ImageUrl;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.chcit.mobile.mvp.receive.api.ReceiveApi;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.FragmentScope;

import javax.inject.Inject;

import com.chcit.mobile.mvp.receive.contract.ReceiveContract;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


@FragmentScope
public class ReceiveModel extends BaseModel implements ReceiveContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public ReceiveModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }
    //获取采购入库信息
    @Override
    public Observable<List<ReceiveBean>> getReceives(String method,JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                                    .requestOnString(method,json)
                                    .map(result -> {
                                        JSONObject resultJson = JSONObject.parseObject(result);
                                        ResultBean data = resultJson.toJavaObject(ResultBean.class);
                                        //ResponseBean<ReceiveBean> data =mGson.<ResponseBean<ReceiveBean>>fromJson(result,ResponseBean.class);
                                        if(resultJson.getBoolean("success")){

                                            if(data.getData().getInteger("total")==0){
                                                throw new BaseException("没有查询到数据！");
                                            }
                                            return data.getRows(ReceiveBean.class);

                                        }else{
                                            throw new Exception("请求失败: "+(resultJson.getString("msg").isEmpty()?"未知错误":resultJson.getString("msg")));
                                        }

                                    }).subscribeOn(Schedulers.io());
    }
    //批量收货
    @Override
    public Observable<ResultBean> doBatchConfirm(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                //.receiveLine(json)
                .request(HttpMethodContains.RECEVIE_BATCH_OK,json)
                .map(jsonObject -> {
                    ResultBean resultBean = mGson.fromJson(jsonObject.toJSONString(),ResultBean.class);
                    if(resultBean.isSuccess()){
                        return resultBean;
                    }else{
                        throw new Exception("请求失败: "+resultBean.getMsg());
                    }
                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<List<AsnResultBean>> queryDataList(PageBean pageBean, QueryListInput queryListInput) {

        JSONObject param = new JSONObject();
        param.putAll(JSONObject.parseObject(JSONObject.toJSONString(pageBean)));
        param.putAll(JSONObject.parseObject(JSONObject.toJSONString(queryListInput)));
        return mRepositoryManager.obtainRetrofitService(ReceiveApi.class)
                .queryListData(param)
                .map(resultJson -> {
                        //ResponseBean<ReceiveBean> data =mGson.<ResponseBean<ReceiveBean>>fromJson(result,ResponseBean.class);
                        if(resultJson.isSuccess()){

                            if(resultJson.getTotal()==0){
                                XToast.warning(mApplication,"没有查询到数据！").show();
                            }
                            return resultJson.getRows(AsnResultBean.class);

                        }else{
                            throw new Exception("请求失败: "+(resultJson.getMsg().isEmpty()?"未知错误":resultJson.getMsg()));
                        }

                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<ImageUrl> uploadImage(String asnId, List<String> media) {
        MultipartBody.Part[] parts = new MultipartBody.Part[media.size()];
        Map<String, RequestBody> mapParams = new HashMap<>();
        RequestBody traceBody = RequestBody.create(MediaType.parse("multipart/form-data"), asnId);
        mapParams.put("asnId", traceBody);
        int cnt = 0;
        for (String m : media) {
            File file = new File(m);
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("headimg[]", file.getName(), requestFile);
            parts[cnt] = filePart;
            cnt++;
        }

        return mRepositoryManager.obtainRetrofitService(ReceiveApi.class)
                .uploadImg(mapParams,parts)
                .subscribeOn(Schedulers.io())
                .map(baseResponse -> {
                    if(baseResponse.isSuccess()){
                        JSONObject data = baseResponse.getData();
                        ImageUrl imageUrl = new ImageUrl(data.getInteger("attachmentId"),data.getString("attachmentUrl"));
                        return imageUrl;
                    }else{
                        throw new Exception("请求失败: "+baseResponse.getMsg());
                    }
                }).subscribeOn(Schedulers.io());
    }


    public Observable<BaseResponse> downImage(String asnId, List<String> media) {
       return null;
    }


    public Observable<List<ImageUrl>> queryImageIds(String asnId) {

        return mRepositoryManager.obtainRetrofitService(ReceiveApi.class)
                //.receiveLine(json)
                .queryImageIds(asnId)
                .map(baseResponse -> {
                    if(baseResponse.isSuccess()){
                        return baseResponse.getRows().toJavaList(ImageUrl.class);
                    }else{
                        throw new Exception("请求失败: "+baseResponse.getMsg());
                    }
                }).subscribeOn(Schedulers.io());
    }

    public Observable<BaseResponse> deleteImage(String iamgeId) {

        return mRepositoryManager.obtainRetrofitService(ReceiveApi.class)
                //.receiveLine(json)
                .deleteImage(iamgeId)
               .subscribeOn(Schedulers.io());
    }
}